
#include "D3D9MaterialManager.h"
#include "D3D9Effect.h"
#include "D3D9Device.h"

namespace sharpShooter
{
	namespace Render
	{



		CD3D9MaterialManager::CD3D9MaterialManager(Device::ISharpShooterDevice *pDevice)
			//:m_pD3D9Device(pDevice)
		{
			m_pD3D9Device = dynamic_cast<Device::CD3D9Device*>(pDevice)->getDevice();
			IMaterial *pMaterial = new IMaterial();
			if (pMaterial != NULL)
			{
				pMaterial->setMaterialType(MT_SOLID);
				//pMaterial->setTexture(0,pTexture);
				IEffect *pEffect = new CD3D9Effect(m_pD3D9Device);
				if (E_ResultSuccessed == pEffect->loadEffectFromString(CONSTDefaultEffectSource))
				{
					m_EffectMap.insert(std::pair<std::string,IEffect*>("Default",pEffect));
					pMaterial->setEffect(pEffect);
				}				
				pMaterial->setAmbientColor(CONSTDefaultColor);
				pMaterial->setDiffuseColor(CONSTDefaultColor);
				pMaterial->setEmissiveColor(CONSTDefaultColor);
				pMaterial->setSpecularColor(CONSTDefaultColor);

				m_DefaultMaterial = pMaterial;
				MaterialMapElement materialPair;
				materialPair.first = pMaterial;
				m_MaterialMap.insert(materialPair);
			}
		}

		CD3D9MaterialManager::~CD3D9MaterialManager()
		{

		}

		IMaterial * CD3D9MaterialManager::addMaterial(
			EMaterialType materialType,
			ITexture *pTexture,
			const char* effectFilePath ,
			Core::CColorRGBAf ambientColor , 
			Core::CColorRGBAf diffuseColor , 
			Core::CColorRGBAf emissiveColor , 
			Core::CColorRGBAf specularColor )
		{
			IMaterial *pMaterial = new IMaterial();
			if (pMaterial != NULL)
			{
				pMaterial->setMaterialType(materialType);
				pMaterial->setTexture(0,pTexture);
				pMaterial->setEffect(getEffect(effectFilePath));
				pMaterial->setAmbientColor(ambientColor);
				pMaterial->setDiffuseColor(diffuseColor);
				pMaterial->setEmissiveColor(emissiveColor);
				pMaterial->setSpecularColor(specularColor);

				MaterialMapElement materialPair;
				materialPair.first = pMaterial;
				m_MaterialMap.insert(materialPair);
			}

			return pMaterial;
		}

		IEffect* CD3D9MaterialManager::getEffect(const std::string &effectFileName)
		{
			EffectMap::iterator iterEffect = m_EffectMap.find(effectFileName);
			if (iterEffect != m_EffectMap.end())
			{
				return iterEffect->second;
			}

			IEffect *pEffect = new CD3D9Effect(m_pD3D9Device);
			if (NULL != pEffect )
			{
				if (E_ResultSuccessed == pEffect->loadEffectFromFile(effectFileName))
				{
					m_EffectMap.insert(std::pair<std::string,IEffect*>(effectFileName,pEffect));
					return pEffect;
				}
				else
				{
					delete pEffect;
					pEffect = NULL;
				}
			}
			return NULL;
		}
	}
}